const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const getType = require('./type.js');

// 创建服务器
const server = http.createServer((req,res)=>{
    console.log(req.url)
    // 因为nodejs每次访问/,都会请求 /favicon.ico，需要阻止访问网站的小图标
    if (req.url === '/favicon.ico') {
        return
    }
    // 对请求资源路径进行解析 --- pathname 就是资源文件名  req.url = 'http://localhost:3000/news'
    let pathname = url.parse(req.url).pathname;
    // console.log(pathname); //  /index.html    
    // 如果访问的是根目录/ ，那我们访问的也是home.html
    pathname = pathname === '/'?'/index.html':pathname;
    // if (pathname === '/') {
    //     pathname = '/home.html'
    // }

    // 获取请求资源文件的后缀名
    let extname = path.extname(pathname);
    // console.log(extname);
    // console.log(path.join(__dirname,'/view',pathname));
    // fs.readFile('请求的资源路径'+pathname,'utf-8',(err,data)=>{})
    // console.log(pathname);
    // console.log(extname);
    // console.log(getType(extname));
    console.log(path.join(__dirname))
    if (extname === '') {
        fs.readFile(path.join(__dirname,'/404.html'),'binary',(err,data)=>{
            
            if(err) return;
            res.writeHead(200,{'content-type':`text/html;charset=utf-8`});
            res.write(data,'binary');
            res.end();
        }) 
    }

    if (extname === '.jpg'||'.png'||'.gif'||'.webp'||'.svg') {
        fs.readFile(path.join(__dirname,pathname),'binary',(err,data)=>{
            if(err) return;
            res.writeHead(200,{'content-type':`${getType(extname)};charset=utf-8`});
            res.write(data,'binary');
            res.end();
        })        
    } else {
        fs.readFile(path.join(__dirname,pathname),'utf-8',(err,data)=>{
            if(err) return;
            res.writeHead(200,{'content-type':`${getType(extname)};charset=utf-8`});
            res.write(data);
            res.end();
        })   
    }

    // 判断登录的请求路径是否是  /login



});

// 监听服务器端口
server.listen(3000,()=>{
    console.log('服务已启动,请访问http://localhost:3000');
})